package com.example.musiccommunity.util;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.example.musiccommunity.bean.Song;

import java.io.IOException;
import java.util.ArrayList;

public class MusicController {
    public MediaPlayer mediaPlayer;
    private ArrayList<Song> songList;
    public int currentPosition = 0;
    private Context context;

    public MusicController(Context context1,ArrayList<Song> songs,int posit) {
        this.songList = songs;
        this.context=context1;
        currentPosition=posit;
        this.mediaPlayer = new MediaPlayer();
        initMediaPlayer();
    }

    private void initMediaPlayer() {

        String url="http://47.93.14.182:8080/workspace/music/"
                +songList.get(currentPosition).getRawResId()+".mp3";
        System.out.println("url="+url);
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        mediaPlayer = new MediaPlayer();
        try {
            // 设置音频流类型
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

            // 设置数据源为网络URL
            mediaPlayer.setDataSource(url);

            // 异步准备媒体播放器
            mediaPlayer.prepareAsync();

            // 准备完成监听器
            mediaPlayer.setOnPreparedListener(mp -> {
                // 准备完成后自动播放
                mp.start();
            });

            // 播放完成监听器
            mediaPlayer.setOnCompletionListener(mp -> nextSong());

            // 错误监听器
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Log.e("MusicController", "播放错误: " + what + ", " + extra);
                return true;
            });

        } catch (IOException e) {
            e.printStackTrace();
            Log.e("MusicController", "初始化MediaPlayer失败: " + e.getMessage());
        }
    }
    // 播放/暂停切换
    public int togglePlay() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            return 1;
        } else {
            mediaPlayer.start();
            return 2;
        }
    }

    // 下一首
    public void nextSong() {
        currentPosition = (currentPosition + 1) % songList.size();
        initMediaPlayer();
        mediaPlayer.start();
    }

    // 上一首
    public void previousSong() {
        currentPosition = (currentPosition - 1 + songList.size()) % songList.size();
        initMediaPlayer();
        mediaPlayer.start();
    }

    // 释放资源
    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
